<template>
  <view class="search-container">
    <!-- 搜索框 -->
    <view class="search-bar">
      <uni-search-bar placeholder="书名/作者/ISBN/出版社" cancelButton="none" v-model="kw" @confirm="handleSearch"
        @clear="handleClear" @input="handleInput">
        <template v-slot:searchIcon>
          <uni-icons type="search" size="18" color="#999"></uni-icons>
        </template>
      </uni-search-bar>
    </view>

    <!-- 搜索建议列表 -->
    <view class="search-results" v-if="searchResults.length > 0">
      <!-- 直接使用 view 包裹内容 -->
      <view class="search-results" v-if="searchResults.length > 0">
        <view class="result-count">共找到 {{total}} 条结果</view>

        <!-- 普通列表渲染 -->
        <book-item v-for="(item, index) in searchResults" :key="index" :book="item" @click="gotoBookInfo(item)" />

        <!-- 加载提示 -->
        <view class="load-more">
          <text v-if="loading">加载中...</text>
          <text v-else-if="noMore">没有更多了</text>
        </view>
      </view>
    </view>

    <!-- 搜索历史 -->
    <view class="history-section" v-else>
      <view class="section-header">
        <text class="section-title">搜索历史</text>
        <view class="action" @click="cleanHistory" v-if="historyList.length > 0">
          <uni-icons type="trash" size="18" color="#999"></uni-icons>
          <text>清空</text>
        </view>
      </view>

      <view class="history-tags" v-if="historyList.length > 0">
        <view class="tag" v-for="(item, index) in historys" :key="index" @click="searchHistory(item)">
          {{item}}
          <uni-icons type="close" size="14" color="#999" @click.stop="removeHistory(index)"></uni-icons>
        </view>
      </view>

      <view class="empty-tip" v-else>
        <uni-icons type="search" size="24" color="#ccc"></uni-icons>
        <text>暂无搜索历史</text>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        timer: null,
        kw: '',
        searchResults: [],
        historyList: [],
        isLoading: false,
        page: 1,
        pageSize: 10,
        total: 0,
        noMore: false
      }
    },
    computed: {
      historys() {
        return [...this.historyList].reverse()
      }
    },
    methods: {
      handleInput(value) {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.kw = value
          if (this.kw.trim()) {
            this.resetSearch()
            this.getSearchList()
          } else {
            this.resetSearch()
          }
        }, 500)
      },

      handleSearch() {
        if (this.kw.trim()) {
          this.resetSearch()
          this.getSearchList()
        }
      },

      handleClear() {
        this.resetSearch()
      },

      resetSearch() {
        this.page = 1
        this.total = 0
        this.noMore = false
        this.searchResults = []
      },

      async getSearchList() {
        if (this.loading || this.noMore) return

        this.loading = true
        try {
          const {
            data
          } = await uni.$http.get('/book/search', {
            kw: this.kw,
            page: this.page,
            size: this.pageSize
          })

          if (data.code !== 1) throw new Error(data.message || '搜索失败')
          this.total = data.data.total || 0
          const newData = data.data.records || []

          if (newData.length < this.pageSize) {
            this.noMore = true
          }

          if (this.page === 1) {
            this.searchResults = newData
            if (newData.length > 0) {
              this.saveSearchHistory()
            } else {
              uni.showToast({
                title: '未找到相关图书',
                icon: 'none'
              })
            }
          } else {
            this.searchResults = [...this.searchResults, ...newData]
          }

          this.page++
        } catch (error) {
          console.error('搜索失败:', error)
          uni.showToast({
            title: error.message || '搜索失败',
            icon: 'none'
          })
        } finally {
          this.loading = false
        }
      },

      loadMore() {
        if (!this.noMore && this.searchResults.length > 0) {
          this.getSearchList()
        }
      },


      gotoBookInfo(item) {
        uni.navigateTo({
          url: `/subpkg/book_info/book_info?id=${item.id}&title=${encodeURIComponent(item.title)}`
        })
      },

      saveSearchHistory() {
        const set = new Set(this.historyList)
        set.delete(this.kw)
        set.add(this.kw)
        this.historyList = Array.from(set)
        uni.setStorageSync('search_history', JSON.stringify(this.historyList))
      },

      cleanHistory() {
        uni.showModal({
          title: '提示',
          content: '确定清空搜索历史吗？',
          success: (res) => {
            if (res.confirm) {
              this.historyList = []
              uni.setStorageSync('search_history', '[]')
            }
          }
        })
      },

      searchHistory(item) {
        this.kw = item
        this.getSearchList()
      },

      removeHistory(index) {
        this.historyList.splice(index, 1)
        uni.setStorageSync('search_history', JSON.stringify(this.historyList))
      }
    },
    onLoad() {
      this.historyList = JSON.parse(uni.getStorageSync('search_history') || '[]')
    },
    onReachBottom() {
      this.loadMore()
    }
  }
</script>

<style lang="scss">
  .search-container {
    padding: 20rpx;
    min-height: 100vh;
    background-color: #f8f8f8;
  }

  .search-bar {
    margin-bottom: 20rpx;
    background-color: #fff;
    border-radius: 10rpx;
    padding: 10rpx;
    box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  }

  .search-results {
    .result-count {
      font-size: 24rpx;
      color: #999;
      padding: 20rpx 0;
    }

    .result-list {
      max-height: calc(100vh - 200rpx);
    }

    .load-more {
      text-align: center;
      padding: 20rpx 0;
      font-size: 24rpx;
      color: #999;
    }
  }

  .history-section {
    background-color: #fff;
    border-radius: 10rpx;
    padding: 20rpx;
    box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;

      .section-title {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
      }

      .action {
        display: flex;
        align-items: center;
        font-size: 24rpx;
        color: #999;

        text {
          margin-left: 5rpx;
        }
      }
    }

    .history-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 15rpx;

      .tag {
        display: flex;
        align-items: center;
        padding: 10rpx 20rpx;
        background-color: #f5f5f5;
        border-radius: 30rpx;
        font-size: 26rpx;
        color: #666;

        .uni-icons {
          margin-left: 10rpx;
        }
      }
    }

    .empty-tip {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 60rpx 0;
      color: #ccc;
      font-size: 26rpx;

      .uni-icons {
        margin-bottom: 20rpx;
      }
    }
  }
</style>
